#include "head.h"

int read_logins_from_file(const char *filename, Login **login_list) {
    FILE *fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("无法打开文件 %s！\n", filename);
        return 0;
    }
    char line[100];
    int count = 0;
    Login *tail = NULL;
    while (fgets(line, sizeof(line), fp) != NULL) {
        Login *new_login = (Login *)malloc(sizeof(Login));
        if (new_login == NULL) {
            printf("内存分配失败！\n");
            fclose(fp);
            return count;
        }
        line[strcspn(line, "\n")] = '\0';
        if (sscanf(line, "%[^,],%s", new_login->name, new_login->passwd) == 2) {
            new_login->next = NULL;
            if (*login_list == NULL) {
                *login_list = new_login;
                tail = new_login;
            } else {
                tail->next = new_login;
                tail = new_login;
            }
            count++;
        } else {
            free(new_login);
        }
    }
    fclose(fp);
    return count;
}

void register_user(Login **login_list, int *lg_count) {
    Login *new_user = (Login *)malloc(sizeof(Login));
    if (new_user == NULL) {
        printf("内存分配失败！\n");
        return;
    }
    FILE *fp = fopen("login.txt", "a");
    if (fp == NULL) {
        printf("无法打开文件！\n");
        free(new_user);
        return;
    }
    printf("请输入用户名：");
    scanf("%19s", new_user->name);
    printf("请输入密码：");
    scanf("%19s", new_user->passwd);
    fprintf(fp, "%s,%s\n", new_user->name, new_user->passwd);
    fclose(fp);

    new_user->next = NULL;
    if (*login_list == NULL) {
        *login_list = new_user;
    } else {
        Login *p = *login_list;
        while (p->next != NULL) {
            p = p->next;
        }
        p->next = new_user;
    }
    (*lg_count)++;
    printf("注册成功！\n");
    printf("用户名：%s\n", new_user->name);
    printf("密码：%s\n", new_user->passwd);
}

int login_user(const Login *login_list) {
    char name[20];
    char passwd[20];
    printf("请输入用户名：");
    scanf("%19s", name);
    printf("请输入密码：");
    scanf("%19s", passwd);
    const Login *p = login_list;
    while (p != NULL) {
        if (strcmp(name, p->name) == 0 && strcmp(passwd, p->passwd) == 0) {
            printf("登录成功！\n");
            return 1;
        }
        p = p->next;
    }
    printf("用户名或密码错误！\n");
    return 0;
}

void free_all_logins(Login **login_list) {
    Login *p = *login_list;
    while (p != NULL) {
        Login *temp = p;
        p = p->next;
        free(temp);
    }
    *login_list = NULL;
}